package internal

import (
	"github.com/name5566/leaf/gate"
	"server/msg"
	"github.com/name5566/leaf/log"
	"fmt"
)

var(
	rooms = make(map[int32]*Room)
	lobbyRooms = make(map[int32]*Room)
	gameRooms = make(map[int32]*Room)
	waitingRooms = make(map[int32]*Room)
	shopRooms = make(map[int32]*Room)
	lobbyRoomMax = 12
	gameRoomMax = 6
	waitingRoomMax = 3
	shopRoomMax = 12
)

func CreateRooms(rType msg.RoomType) int32{
	rooms:= GetRooms(rType)
	roomId := int32(len(rooms))
	room := newRoom(roomId, rType)
	rooms[roomId] = room

	return roomId
}

func AddPlayer(agent gate.Agent, id int32, roomType msg.RoomType) {
	rooms := GetRooms(roomType)
	index := int32(len(rooms))-1
	if index < 0 {
		index = 0
	}

	room := rooms[index]

	if room == nil {
		index = CreateRooms(roomType)
		room = rooms[index]
	} else {
		if len(room.roomPlayers) > GetRoomsMax(roomType) {
			index = CreateRooms(roomType)
		}
	}

	if room.roomPlayers == nil {
		agent.WriteMsg(&msg.JoinFaild{
			PlayerId:id,
			ErrCode:0,
		})

		return
	}

	room.roomPlayers[id] = agent
	player:= playerID2Player[id]

	if player.room != nil {
		if player.room.roomType != roomType {
			delete(player.room.roomPlayers, id)
			for _, p := range player.room.roomPlayers {
				fmt.Println("leave id", id)
				p.WriteMsg(&msg.LeaveRoom{
					PlayerId: id,
				})
			}
		}
	}

	player.room = room
}

func GetRooms(roomType msg.RoomType) map[int32]*Room{
	switch roomType {
	case msg.RoomType_game:
		return gameRooms
	case msg.RoomType_lobby:
		return lobbyRooms
	case msg.RoomType_shop:
		return shopRooms
	case msg.RoomType_wiating:
		return waitingRooms
	default:
		log.Error("dont have room type")
		return rooms
	}
}

func GetRoomsMax(roomType msg.RoomType) int{
	switch roomType {
	case msg.RoomType_game:
		return gameRoomMax
	case msg.RoomType_lobby:
		return lobbyRoomMax
	case msg.RoomType_shop:
		return shopRoomMax
	case msg.RoomType_wiating:
		return waitingRoomMax
	default:
		return 0
	}
}
